package com.example.demo.utils;

import org.springframework.stereotype.Component;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import java.awt.font.LineMetrics;
@Component
public class  WatermarkUtils {

    public static void addTextWatermark(String inputImagePath, String outputImagePath, String text, Color color, Font font, float lineSpacing) {
        try {
            File inputImageFile = new File(inputImagePath);
            BufferedImage inputImage = ImageIO.read(inputImageFile);

            Graphics2D graphics2D = inputImage.createGraphics();
            graphics2D.setColor(color);
            graphics2D.setFont(font);

            // 设置行间距
            graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            LineMetrics lineMetrics = font.getLineMetrics(text, graphics2D.getFontRenderContext());
            float lineHeight = lineMetrics.getHeight() * lineSpacing;

            // 拆分文本为多行
            List<String> lines = splitTextIntoLines(text, font, inputImage.getWidth());

            // 逐行添加水印
            int y = inputImage.getHeight() / 2 - (lines.size() * graphics2D.getFontMetrics().getHeight()) / 2;
            for (String line : lines) {
                int textWidth = graphics2D.getFontMetrics().stringWidth(line);
                int x = (inputImage.getWidth() - textWidth) / 2;
                if (textWidth <= inputImage.getWidth()) { // 检查是否超出了图片宽度
                    graphics2D.drawString(line, x, y);
                } else {
                    int start = 0;
                    int end = 0;
                    while (start < line.length()) {
                        // 找到可以放到当前行的最后一个单词的下标
                        while (end < line.length()) {
                            end++;
                            if (end == line.length())
                                break;
                            if (graphics2D.getFontMetrics().stringWidth(line.substring(start, end + 1)) > inputImage.getWidth())
                                break;
                        }
                        // 如果只有一个单词就超过了图片宽度，直接放到下一行
                        if (start == 0 && end == 0) {
                            end = line.length() - 1;
                        }
                        // 将当前行的内容添加到图片上
                        String subline = line.substring(start, end);
                        textWidth = graphics2D.getFontMetrics().stringWidth(subline);
                        x = (inputImage.getWidth() - textWidth) / 2;
                        graphics2D.drawString(subline, x, y);
                        // 更新start, end和y坐标
                        start = end;
                        y += lineHeight;
                    }
                }
                y += lineHeight;
            }

            graphics2D.dispose();

            File outputImageFile = new File(outputImagePath);
            ImageIO.write(inputImage, "png", outputImageFile);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static List<String> splitTextIntoLines(String text, Font font, int lineWidth) {
        List<String> lines = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        String[] words = text.split("\\s+");
        Graphics2D graphics2D = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB).createGraphics();
        graphics2D.setFont(font);
        for (String word : words) {
            if (graphics2D.getFontMetrics().stringWidth(sb + word) > lineWidth) {
                lines.add(sb.toString());
                sb.setLength(0);
            }
            sb.append(word).append(" ");
        }
        lines.add(sb.toString());
        return lines;
    }

}